<?php
namespace App\Admin\Models;
use Common\BaseModel;
use Common\CommonAd;

class  OrderCommissions extends BaseModel
{
    protected $res;
    public $key;

    public function getSource()
    {
        return "w_order_commissions";
    }

    public function initialize()
    {
        parent::initialize();
    }


    /**
     * @func 获取某时间段粉丝订单数量 自购订单数量 以前的
     * @param $user_id 用户id
     * @param $start_end_time 开始时间和结束时间
     * @param $order_channel 所属平台 taobao pinduoduo jd 如果没有，则查找三个平台的总和
     * @return array 以平台名称作为键 统计作为结果
     */
    public function getFansOrderCount($user_id, $start_end_time, $order_channel = '')
    {
        if ($order_channel) {
            $conditions = "user_id = ?1 AND tk_create_time >= ?2 AND tk_create_time < ?3 AND order_channel = ?4 AND commission_type=2";
            $parameters = array(1 => $user_id, 2 => $start_end_time['start_at'], 3 => $start_end_time['end_at'], 4 => $order_channel);
        } else {
            $conditions = "user_id = ?1 AND tk_create_time >= ?2 AND tk_create_time < ?3 AND commission_type=2";
            $parameters = array(1 => $user_id, 2 => $start_end_time['start_at'], 3 => $start_end_time['end_at']);
        }
        $count_array = $this:: count(array(
            $conditions,
            "column" => "*",
            "group"  => "order_channel",
            "bind"   => $parameters
        ));
        $new_array   = array();
        foreach ($count_array as $key => $value) {
            $new_array[$value['order_channel']] = $value['rowcount'];
        }
        return $new_array;
    }


    public function getFansOrderCounts($user_id, $start_end_time, $order_channel = '')
    {
        if ($order_channel) {
            $conditions = "OrderCommissions.user_id = {$user_id} and OrderCommissions.commission_type=2 and  OrderCommissions.order_status in (2,4,6)";
        } else {
            $conditions = "OrderCommissions.user_id = {$user_id} and OrderCommissions.commission_type=2 and OrderCommissions.tk_create_time>='{$start_end_time['start_at']}' and OrderCommissions.tk_create_time<='{$start_end_time['end_at']}' and OrderCommissions.order_status in (2,4,6)";
        }
        $phql      = "SELECT count(OrderCommissions.id) as rowcount,OrderCommissions.order_channel FROM OrderCommissions LEFT JOIN Orders ON Orders.order_id = OrderCommissions.order_id
                where  " . $conditions . " group by OrderCommissions.order_channel";
        $rows      = $this->modelsManager->executeQuery($phql);
        $new_array = array();
        foreach ($rows as $key => $value) {
            $new_array[$value['order_channel']] = $value['rowcount'];
        }
        return $new_array;
    }


    /**
     * 用户付款预估收益（自购+间接）三个平台的总和
     * @param $start_end_time 开始时间和结束时间
     */
    public function getOrderChannelEstimateCommission($start_end_time)
    {
        $conditions  = "tk_create_time >= ?2 AND tk_create_time < ?3 AND order_status in (2,4,6)";
        $parameters  = array(2 => $start_end_time['start_at'], 3 => $start_end_time['end_at']);
        $money_array = $this:: SUM(array(
            $conditions,
            "column" => "money+money_plus",
            "bind"   => $parameters
        ));
        return $money_array ? $money_array : 0;
    }


    /**
     * 计算结算预估佣金
     * @param $user_id 用户id
     * @param $start_end_time 开始时间和结束时间
     * @param $order_channel 所属平台 taobao pinduoduo jd 如果没有，则查找三个平台的总和
     */
    public function getOrderSettlementCommission($start_end_time, $order_channel = "")
    {
        if ($order_channel) {
            $conditions = "tk_earning_time >= ?2 AND tk_earning_time < ?3 AND order_channel = ?4 AND order_status in (4,6)";
            $parameters = array(2 => $start_end_time['start_at'], 3 => $start_end_time['end_at'], 4 => $order_channel);
        } else {
            $conditions = "tk_earning_time >= ?2 AND tk_earning_time < ?3 AND order_status in (4,6)";
            $parameters = array(2 => $start_end_time['start_at'], 3 => $start_end_time['end_at']);
        }
        $money_array = $this:: SUM(array(
            $conditions,
            "column" => "money+money_plus",
            "bind"   => $parameters
        ));
        return $money_array ? $money_array : 0;
    }


    /**
     * @func 根据用户时间获取各个平台的数据总和 自购订单数量
     * @param $user_id 用户id
     * @param $start_end_time 开始时间和结束时间
     * @param $order_channel 所属平台 taobao pinduoduo jd 如果没有，则查找三个平台的总和
     * @return array 以平台名称作为键 统计作为结果
     */
    public function getOrderCount($user_id, $start_end_time, $order_channel = '')
    {
        if ($order_channel) {
            $conditions = "user_id = ?1 AND tk_create_time >= ?2 AND tk_create_time < ?3 AND order_channel = ?4 and commission_type=1 and order_status in (2,4,6)";
            $parameters = array(1 => $user_id, 2 => $start_end_time['start_at'], 3 => $start_end_time['end_at'], 4 => $order_channel);
        } else {
            $conditions = "user_id = ?1 AND tk_create_time >= ?2 AND tk_create_time < ?3 and commission_type=1 and order_status in (2,4,6)";
            $parameters = array(1 => $user_id, 2 => $start_end_time['start_at'], 3 => $start_end_time['end_at']);
        }

        $count_array = $this::count(array(
            $conditions,
            "columns" => "*",
            "group"   => "order_channel",
            "bind"    => $parameters
        ));

        $new_array = array();
        foreach ($count_array as $key => $value) {
            $new_array[$value['order_channel']] = $value['rowcount'];//order_channel
        }
        return $new_array;
    }


    /**
     * 列出有单的会员
     */
    public function orderuserlist($params)
    {
        $conditions = '';
        if ($params['keywords']) {
            $conditions = "AND (Member.phone like '%{$params['keywords']}%' or Member.nickname like '%{$params['keywords']}%')";
        }
        if (isset($params['created_at']) && !empty($params['created_at'])) {
            if ($conditions) {
                $conditions .= " AND (Member.tk_create_time >='{$params['created_at'][0]}' and Member.tk_create_time <= '{$params['created_at'][1]}')";
            } else {
                $conditions = "AND (Member.tk_create_time >='{$params['created_at'][0]}' and Member.tk_create_time <= '{$params['created_at'][1]}')";
            }
        }
        $phql = "SELECT Member.id,Member.nickname,Member.phone,Member.level_id,SUM(OrderCommissions.money) as money
                FROM OrderCommissions LEFT JOIN Member ON OrderCommissions.user_id = Member.id
                WHERE Member.is_appuser in(0,1) {$conditions}
				GROUP BY OrderCommissions.user_id";
        $rows = $this->modelsManager->executeQuery($phql);
        return $rows;
    }


    /**
     * @func 自购订单和粉丝订单出单
     * @param $param
     * @return mixed
     */
    public function getOrderList($param)
    {
        if ($param['commission_type'] == 1) {//自推出单
            $conditions = "OrderCommissions.user_id =" . $param['user_id'] . ' and  OrderCommissions.commission_type=1';
        } else {//粉丝出单
            $conditions = "OrderCommissions.user_id =" . $param['user_id'] . ' and OrderCommissions.commission_type=2';
        }
        if (isset($param['order_status']) && !empty($param['order_status'])) {
            $conditions .= " AND Orders.order_status IN (" . $param['order_status'] . ")";
        }
        $phql = "SELECT Orders.id,Orders.user_id,Orders.order_id,Orders.order_status,Orders.goods_name,Orders.goods_id,Orders.goods_pic,Orders.site,Orders.price,Orders.pay_money,Orders.commition,Orders.income_rate,Orders.order_create_time,Orders.order_paid_time,Orders.order_earning_time,Orders.is_settlement,
                OrderCommissions.money,OrderCommissions.money_plus,OrderCommissions.commission_type
                FROM OrderCommissions LEFT JOIN Orders ON Orders.order_id = OrderCommissions.order_id
				where  " . $conditions . "  GROUP BY Orders.user_id,Orders.order_id  order by Orders.order_create_time DESC";
        $rows = $this->modelsManager->executeQuery($phql);
        return $rows;
    }


    /**
     * 计算平台所有佣金
     * @param $user_id 用户id
     * @param $start_end_time 开始时间和结束时间
     * @param $order_channel 所属平台 taobao pinduoduo jd 如果没有，则查找三个平台的总和
     */
    public function getOrderCommissionCount($start_end_time = [], $order_channel = "")
    {
        if ($order_channel) {
            $conditions = "tk_earning_time >= ?2 AND tk_earning_time < ?3 AND order_channel = ?4 AND order_status in (4,6)";
            $parameters = array(2 => $start_end_time['start_at'], 3 => $start_end_time['end_at'], 4 => $order_channel);
        } else {
            $conditions = "";
            $parameters = [];
        }
        $money_array = $this:: SUM(array(
            $conditions,
            "column" => "money+money_plus",
            "bind"   => $parameters
        ));
        return $money_array ? $money_array : 0;
    }


    /**
     * 计算平台所有佣金
     * @param $user_id 用户id
     * @param $start_end_time 开始时间和结束时间
     * @param $order_channel 所属平台 taobao pinduoduo jd 如果没有，则查找三个平台的总和
     */
    public function getOrderCommissio($params = [])
    {
        $conditions = "level_type<>''";
        if (isset($params['commission_type']) && !empty($params['commission_type'])) {
            if ($conditions) {
                $conditions .= " AND OrderCommissions.commission_type={$params['commission_type']}";
            } else {
                $conditions .= "OrderCommissions.commission_type={$params['commission_type']}";
            }
        }

        if (isset($params['order_status']) && !empty($params['order_status'])) {
            if ($conditions) {
                $conditions .= " AND Orders.order_status IN ({$params['order_status']})";
            } else {
                $conditions .= "Orders.order_status IN ({$params['order_status']})";
            }
        }
        $phql = "SELECT Orders.id,Orders.user_id,Orders.order_id,Orders.order_status,Orders.goods_name,Orders.goods_id,
                Orders.goods_pic,Orders.site,Orders.price,Orders.pay_money,Orders.commition,Orders.income_rate,
                Orders.order_create_time,Orders.order_paid_time,Orders.order_earning_time,Orders.is_settlement,
                OrderCommissions.money,OrderCommissions.money_plus,OrderCommissions.commission_type,
                Member.phone
                FROM OrderCommissions 
                LEFT JOIN Orders ON Orders.order_id = OrderCommissions.order_id
                LEFT JOIN Member ON Member.id = OrderCommissions.user_id
				WHERE  " . $conditions . "  ORDER BY OrderCommissions.tk_create_time DESC";
        $rows = $this->modelsManager->executeQuery($phql);
        return $rows;
    }

    public function orderCompare($today, $lastday)
    {
        $condition = "order_create_time >= '{$today['start_at']}' and order_create_time <= '{$today['end_at']}'";
        $todayInfo = $this::count(
            $condition
        );
        $condition = "order_create_time >= '{$lastday['start_at']}' and order_create_time <= '{$lastday['end_at']}'";
        $lastInfo  = $this::count(
            $condition
        );
        return $todayInfo - $lastInfo;
    }

    public function userTop($data)
    {
        $start      = date('Y-m-d H:i:s', mktime(0, 0, 0, date('m'), 1, date('Y')));
        $end        = date('Y-m-d H:i:s', mktime(23, 59, 59, date('m'), date('t'), date('Y')));
        $conditions = 'is_virtual = 0 and order_status in (2,4,6)';
        if (isset($data['start_time']) && !empty($data['start_time'])) {
            $conditions .= " and tk_create_time >= '{$data['start_time']}'";
        } else {
            $conditions .= " and tk_create_time >= '{$start}'";
        }
        if (isset($data['end_time']) && !empty($data['end_time'])) {
            $conditions .= " and tk_create_time <= '{$data['end_time']}'";
        } else {
            $conditions .= " and tk_create_time <= '{$end}'";
        }

        if (isset($data['phone']) && !empty($data['phone'])) {
            $userDb = new User();
            $info   = $userDb->findFirstByPhone($data['phone']);
            if (!$info) {
                return [];
            }
            $conditions .= " and user_id = '{$info->id}'";
        }

        if (isset($data['invite_code']) && !empty($data['invite_code'])) {
            $userDb    = new User();
            $userWhere = "invite_code = '{$data['invite_code']}' or exclusive_code = '{$data['invite_code']}'";
            $info      = $userDb->findFirst($userWhere);
            if (!$info) {
                return [];
            }
            $where['conditions'] = "referer_id = {$info->id}";
            $where['columns']    = "id";
            $xiajiId             = $userDb->find($where)->toarray();
            if (empty($xiajiId)) {
                return [];
            }
            $idstr      = implode(',', array_column($xiajiId, 'id'));
            $conditions .= " and user_id in ($idstr) ";
        }
        if (isset($data['alipay_account']) && !empty($data['alipay_account'])) {
            $userDb    = new User();
            $userWhere = "alipay_account = '{$data['alipay_account']}'";
            $info      = $userDb->findFirst($userWhere);
            if (!$info) {
                return [];
            }
            $conditions .= " and user_id = '{$info->id}'";
        }

        if (isset($data['level_id']) && !empty($data['level_id'])) {
            $userDb                   = new User();
            $levelWhere['conditions'] = "level_id = '{$data['level_id']}'";
            $levelWhere['columns']    = "id";
            $info                     = $userDb->find($levelWhere)->toarray();
            if (empty($info)) {
                return [];
            }
            $ids        = implode(',', array_column($info, 'id'));
            $conditions .= " and user_id in ($ids)";
        }
        $cate_list = $this::find(
            array(
                $conditions,
                'columns' => 'user_id,sum(money) + sum(money_plus) as Monthmoney',
                "order"   => 'money desc',
                "group"   => 'user_id',
                "limit"   => 10,
            ))->toarray();
        if (!empty($cate_list)) {
            $toDay     = CommonAd::timeChange(1);
            $yesterDay = CommonAd::timeChange(2);
            $sevenDay  = CommonAd::timeChange(3);
            $lastMonth = CommonAd::timeChange(9);
            $thisMonth = CommonAd::timeChange(8);

            $user = new User();
            foreach ($cate_list as $key => $val) {
                $userInfo = $user->findFirstById($val['user_id']);
                if ($userInfo) {
                    $refererInfo = $user->findFirstById($userInfo->referer_id);
                    if ($refererInfo) {
                        $cate_list[$key]['referer_name']           = $refererInfo->nickname ? $refererInfo->nickname : $refererInfo->wx_nickname;
                        $cate_list[$key]['referer_code']           = $refererInfo->invite_code;
                        $cate_list[$key]['referer_exclusive_code'] = $refererInfo->exclusive_code;
                    }
                    $cate_list[$key]['nickname']       = $userInfo->nickname ? $userInfo->nickname : $userInfo->wx_nickname;
                    $cate_list[$key]['invite_code']    = $userInfo->invite_code;
                    $cate_list[$key]['exclusive_code'] = $userInfo->exclusive_code;
                    $cate_list[$key]['alipay_account'] = $userInfo->alipay_account;
                    $cate_list[$key]['phone']          = $userInfo->phone;
                    $cate_list[$key]['tb_rid']         = $userInfo->tb_rid;
                    $cate_list[$key]['jd_pid']         = $userInfo->jd_pid;
                    $cate_list[$key]['pdd_pid']        = $userInfo->pdd_pid;
                    $cate_list[$key]['level_name']     = $userInfo->level_name($userInfo->level_id);
                    $cate_list[$key]['toDay']          = $this->userEstimate($toDay, $val['user_id']);
                    $cate_list[$key]['yesterDay']      = $this->userEstimate($yesterDay, $val['user_id']);
                    $cate_list[$key]['sevenDay']       = $this->userEstimate($sevenDay, $val['user_id']);
                    $cate_list[$key]['thisMonth']      = $this->userEstimate($thisMonth, $val['user_id']);
                    $cate_list[$key]['lastMonth']      = $this->userEstimate($lastMonth, $val['user_id']);
                    $cate_list[$key]['countMoney']     = $this->userEstimate('', $val['user_id']);
                    $cate_list[$key]['oneCount']       = $user->getDirectFansCount($val['user_id'], []);
                    $path                              = $userInfo->path . ',' . $userInfo->referer_id;
                    $cate_list[$key]['twoCount']       = $user->getIndirectFansCount($val['user_id'], $path, []);
                    $cate_list[$key]['fens']           = $cate_list[$key]['oneCount'] + $cate_list[$key]['twoCount'];
                    $cate_list[$key]['active']         = $user->getIndirectFansCount($val['user_id'], $path, ['updated_at' => $toDay['start_at']]);

                }
            }
        }
        return $cate_list;
    }

    public function userEstimate($data = '', $user = '')
    {
        $where = "is_virtual = 0 ";
        if (isset($user) && !empty($user)) {
            $where .= " and user_id = {$user}";
        }
        if (isset($data['start_at']) && !empty($data['start_at']) && isset($data['end_at']) && !empty($data['end_at'])) {
            $where .= " and tk_create_time >= '{$data['start_at']}' and tk_create_time <= '{$data['end_at']}'";
        }
        $conditions['conditions'] = $where;
        $conditions['column']     = 'money +money_plus';
        return $this::sum($conditions);
    }


    public function self_order_commition_sum($user_id)
    {
        $conditions = "user_id={$user_id} and commission_type=1 and order_status in(4,6)";
        $total_sum  = $this->sum(array(
                $conditions,
                'column' => 'money+money_plus'
            )
        );
        return $total_sum ? $total_sum : '0.00';
    }


    //我的佣金明细
    public function get_my_order_commition($params = [], $method = 'find')
    {
        $page = intval($params['page']);
        $size = intval($params['limit']);
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $conditions = "user_id={$params['user_id']} and money<>0";

        if (isset($params['type']) && !empty($params['type'])) {
            switch ($params['type']) {
                case 'self':
                    $conditions .= " and buyer_id={$params['user_id']}";
                    break;
                case 'other':
                    $conditions .= " and buyer_id<>{$params['user_id']}";
                    break;
            }
        }

        if ($method == 'find') {
            $cate_list = $this::find(
                array(
                    $conditions,
                    "order"  => 'id desc',
                    'limit'  => $size,
                    'offset' => $page
                )
            )->toarray();
        } else {
            $cate_list = $this->count(array(
                $conditions,
            ));
        }
        return $cate_list;
    }


    //我的自购订单
    public function get_selfmy_order_commition($params = [], $method = 'find')
    {
        $page = isset($params['page']) ? intval($params['page']) : 1;
        $size = isset($params['limit']) ? intval($params['limit']) : 10;
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $conditions = "user_id={$params['user_id']} and money<>0 and commission_type=1";
        if ($method == 'find') {
            $cate_list = $this::find(
                array(
                    $conditions,
                    "order"  => 'id desc',
                    'limit'  => $size,
                    'offset' => $page
                )
            )->toarray();
        } else {
            $cate_list = $this->count(array(
                $conditions,
            ));
        }
        return $cate_list;
    }


    //我的自购佣金总和
    public function get_my_self_sum($user_id)
    {
        $conditions = "user_id={$user_id} and money<>0 and commission_type=1 and order_status in (2,4,6)";
        $cate_list  = $this::sum(
            array(
                $conditions,
                'column' => 'money+money_plus'
            )
        );
        return $cate_list ? $cate_list : '0.00';
    }


    //我的确认收货
    public function get_my_all_sum($user_id)
    {
        $conditions = "user_id={$user_id} and money<>0 and order_status in(6)";
        $cate_list  = $this::sum(
            array(
                $conditions,
                'column' => 'money+money_plus'
            )
        );
        return $cate_list ? $cate_list : '0.00';
    }

    /**
     * @func 根据用户时间获取各个平台结算的数据总和 自购订单数量
     * @param $user_id 用户id
     * @param $start_end_time 开始时间和结束时间
     * @param $order_channel 所属平台 taobao pinduoduo jd 如果没有，则查找三个平台的总和
     * @return array 以平台名称作为键 统计作为结果
     */
    public function getUserSettlementCount($user_id, $start_end_time, $status = 0)
    {
        if ($status == 1) {
            $conditions = "user_id = ?1 AND tk_create_time >= ?2 AND tk_create_time < ?3  and order_status in (2,4,6)";
        } else {
            $conditions = "user_id = ?1 AND tk_earning_time >= ?2 AND tk_earning_time < ?3  and order_status in (2,4,6)";
        }
        $parameters = array(1 => $user_id, 2 => $start_end_time['start_at'], 3 => $start_end_time['end_at']);

        $count_array = $this::find(array(
            $conditions,
            "columns" => "sum(money+money_plus) as count,order_channel",
            "group"   => "order_channel",
            "bind"    => $parameters
        ));

        $new_array = array();
        foreach ($count_array as $key => $value) {
            $new_array[$value['order_channel']] = $value['count'];//order_channel
        }
        return $new_array;
    }

    /**
     * @func 根据用户时间获取各个平台结算的数据总和 自购订单数量
     * @param $user_id 用户id
     * @param $start_end_time 开始时间和结束时间
     * @param $order_channel 所属平台 taobao pinduoduo jd 如果没有，则查找三个平台的总和
     * @return array 以平台名称作为键 统计作为结果
     */
    public function getFkCount($user_id, $start_end_time)
    {
        $conditions = "user_id = ?1 AND tk_create_time >= ?2 AND tk_create_time < ?3  and order_status in (2,4,6)";

        $parameters = array(1 => $user_id, 2 => $start_end_time['start_at'], 3 => $start_end_time['end_at']);

        $count_array = $this::find(array(
            $conditions,
            "columns" => "count(*) as count,order_channel",
            "group"   => "order_channel",
            "bind"    => $parameters
        ));

        $new_array = array();
        foreach ($count_array as $key => $value) {
            $new_array[$value['order_channel']] = $value['count'];//order_channel
        }
        return $new_array;
    }

    public function commissionSum()
    {
        $conditions = 'order_status in (2,4,6)';
        return $this::SUM(array(
            $conditions,
            'column' => 'money'
        ));
    }

    /**
     * 列表
     * @param $params
     * @param string $method
     * @return int
     */
    public function getsettlement($params, $method = 'list')
    {
        $page = isset($params['page']) ? intval($params['page']) : 1;
        $size = isset($params['limit']) ? intval($params['limit']) : 10;
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $where = "is_virtual=0 and settlement_type = 0 and order_status IN (4, 6) and  tk_earning_time BETWEEN '" . $params['data'][0] . "' AND '" . $params['data'][1] . "'";
        $user  = new User();
        if (isset($params['phone']) && !empty($params['phone'])) {
            $users = $user->findFirstByPhone($params['phone']);
            if ($users) {
                $where .= ' and user_id = ' . $users->id;
            } else {
                $where .= ' and user_id = 99999999';
            }
        }

        if ($method == 'list') {
            $condition = [
                'conditions' => $where,
                'columns'    => 'user_id, SUM(money + money_plus) AS money',
                'group'      => 'user_id',
                'limit'      => $size,
                'offset'     => $page
            ];
            $list      = $this->find($condition)->toarray();
            if (!empty($list)) {
                $level             = new LevelV2();
                $user_month_income = new UserMonthIncome();
                $dates             = date('Y-m', strtotime($params['data'][0]));
                foreach ($list as &$val) {

                    $inWhere = "month = '$dates' and user_id = {$val['user_id']}";
                    $isIn    = $user_month_income->findFirst($inWhere);
                    if ($isIn) {
                        $val['is_set'] = true;
                    } else {
                        $val['is_set'] = false;
                    }
                    $userInfo          = $user->findFirstById($val['user_id']);
                    $val['avatar']     = '';
                    $val['nickname']   = '';
                    $val['level_name'] = '';
                    if ($userInfo) {
                        $val['avatar']     = $userInfo->avatar;
                        $val['nickname']   = $userInfo->nickname;
                        $val['level_name'] = $level->find_by_level_name($userInfo->level_id);
                    }
                    $params['user_id'] = $val['user_id'];
                    $siteCount         = $this->order_channel_count($params);
                    $val['taobao']     = 0;
                    $val['jd']         = 0;
                    $val['pdd']        = 0;
                    $val['vph']        = 0;
                    $val['suning']     = 0;
                    $val['qita']       = 0;
                    if (!empty($siteCount)) {
                        foreach ($siteCount as $value) {
                            switch ($value['order_channel']) {
                                case 'haodanku';
                                    $val['taobao'] += $value['money'];
                                    break;
                                case 'elm';
                                    $val['taobao'] += $value['money'];
                                    break;
                                case 'jd';
                                    $val['jd'] += $value['money'];
                                    break;
                                case 'pdd';
                                    $val['pdd'] += $value['money'];
                                    break;
                                case 'vph';
                                    $val['vph'] += $value['money'];
                                    break;
                                case 'suning';
                                    $val['suning'] += $value['money'];
                                    break;
                                default:
                                    $val['qita'] += $value['money'];
                                    break;
                            }

                        }
                    }
                    $total = $val['taobao'] + $val['jd'] + $val['pdd'] + $val['vph'] + $val['suning'] + $val['qita'];
                    $val['total'] = CommonAd::number_randtwo($total);
                }
            }
            return $list;
        } else {
            $condition = [
                'conditions' => $where,
                'group'      => 'user_id',
            ];
            return count($this->count($condition));
        }
    }

    /**
     * 详情
     */
    public function detareport_detail($params)
    {
        $page = intval($params['page']);
        $size = intval($params['limit']);
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $condition       = "settlement_type = 0 and user_id = {$params['user_id']}  and is_virtual=0 and order_status IN (4, 6) and tk_earning_time BETWEEN '" . $params['data'][0] . "' AND '" . $params['data'][1] . "'";
        $cate_list       = $this::find(
            array(
                $condition,
                "order"  => 'id desc',
                'limit'  => $size,
                'offset' => $page
            ))->toarray();
        $result['total'] = $this::count($condition);
        if (!empty($cate_list)) {
            foreach ($cate_list as &$val) {
                switch ($val['order_channel']) {
                    case 'haodanku':
                        $val['site_name'] = '淘宝/天猫';
                        break;
                    case 'jd':
                        $val['site_name'] = '京东';
                        break;
                    case 'pdd':
                        $val['site_name'] = '拼多多';
                        break;
                    case 'elm':
                        $val['site_name'] = '饿了么';
                        break;
                    case 'vph':
                        $val['site_name'] = '唯品会';
                        break;
                    case 'suning':
                        $val['site_name'] = '苏宁';
                        break;
                    default:
                        $val['site_name'] = '其他';
                }
            }
        }
        $result['item'] = $cate_list;
        return $result;
    }

    public function order_channel_count($params)
    {
        $condition = [
            'conditions' => "user_id = {$params['user_id']} and is_virtual=0 and order_status IN (4, 6) and  tk_earning_time BETWEEN '" . $params['data'][0] . "' AND '" . $params['data'][1] . "'",
            'columns'    => 'order_channel,SUM(money + money_plus) AS money',
            'group'      => 'order_channel',
        ];
        return $this->find($condition)->toarray();
    }

    public function order_count($params)
    {
        $condition = [
            'conditions' => "settlement_type = 0 and is_virtual=0 and order_status IN (4, 6) and  tk_earning_time BETWEEN '" . $params['data'][0] . "' AND '" . $params['data'][1] . "'",
            'columns'    => 'order_channel,SUM(money + money_plus) AS money',
            'group'      => 'order_channel',
        ];
        return $this->find($condition)->toarray();
    }

    public function order_count_settlement()
    {
        $condition = [
            'conditions' => "settlement_type = 1 and is_virtual=0 and order_status IN (4, 6) ",
            'columns'    => 'order_channel,SUM(money + money_plus) AS money',
            'group'      => 'order_channel',
        ];
        return $this->find($condition)->toarray();
    }

    public function order_user_list($params)
    {
        $condition = [
            'conditions' => "settlement_type = 0 and is_virtual=0 and order_status IN (4, 6) and  tk_earning_time  >= '{$params['data'][0]}' and tk_earning_time <= '{$params['data'][1]}' ",
            'columns'    => 'user_id',
            'group'      => 'user_id',
        ];
        return $this->find($condition)->toarray();
    }

    public function get_month_user($start_end_time)
    {
        $conditions = "settlement_type = 0 and user_id in ({$start_end_time['user_id']}) and is_virtual=0 and order_status IN (4, 6) and  tk_earning_time BETWEEN '" . $start_end_time['start_at'] . "' AND '" . $start_end_time['end_at'] . "'";
        $condition  = [
            'conditions' => $conditions,
            'columns'    => 'user_id, SUM(money + money_plus) AS money',
            'group'      => 'user_id',
        ];
        $res        = $this->find($condition)->toArray();

        $orderId = $this->find([
            'conditions' => $conditions,
            //            'columns'    => 'id,order_id'
        ]);


        if (!empty($orderId->toarray())) {
            $orderIdArr = [];
            foreach ($orderId as $val) {
                $val->settlement_type = 1;
                $orderIdArr[]         = $val->order_id;
                if (!$val->save()) {
                    return false;
                }
            }
            $order      = new Orders();
            $orderIdStr = implode(',', $orderIdArr);
            $orderlist  = $order->find([
                'conditions' => "order_id in ($orderIdStr)"
            ]);
            if (!empty($orderlist)) {
                foreach ($orderlist as $value) {
                    $value->is_settlement = 1;
                    if (!$value->save()) {
                        return false;
                    }
                }
            }
        }

        return $res;
    }

    /**
     * 预估收益
     */
    public function yugu_money($user_id)
    {
        $where['conditions'] = "user_id = $user_id and order_status in (2,4,6)";
        $where['columns']    = "sum(money) as money";
        $count               = $this->findFirst($where);
        return $count->money ? $count->money : 0;
    }

    /**
     * 0.总佣金  2.今日 3.昨日 4.7日 5.30日
     */
    public function order_commision_money($user_ids)
    {
        $result['all_money']   = $this->commission_money($user_ids, []);
        $today                 = CommonAd::timeChange(1);
        $result['today_money'] = $this->commission_money($user_ids, $today);
        $yestoday              = CommonAd::timeChange(2);
        $result['yestoday']    = $this->commission_money($user_ids, $yestoday);
        $weekday               = CommonAd::timeChange(3);
        $result['weekday']     = $this->commission_money($user_ids, $weekday);
        $monthday              = CommonAd::timeChange(5);
        $result['monthday']    = $this->commission_money($user_ids, $monthday);
        return $result;
    }

    public function commission_money($user_ids, $data_times)
    {
        $conditions = 'order_status in(2,4,6)';
        if (isset($data_times['start_at']) && !empty($data_times['start_at']) && isset($data_times['end_at']) && !empty($data_times['end_at'])) {
            $conditions = "tk_create_time>='{$data_times['start_at']}' and tk_create_time<= '{$data_times['start_at']}'";
        }
        if ($user_ids) {
            if ($conditions) {
                $conditions .= " AND user_id in($user_ids)";
            } else {
                $conditions = "user_id in($user_ids)";
            }
        }
        $money = $this->sum(array(
            $conditions,
            "column" => "money",
        ));
        return $money ? $money : 0;
    }

    public function monthZero()
    {
        $time                = CommonAd::timeChange(8);
        $where['conditions'] = "tk_create_time >= '{$time['start_at']}' and tk_create_time <= '{$time['end_at']}' and order_status in (2,4,6) and is_free = 1";
        $where['columns']    = "count(*) count";
        $count               = $this->findFirst($where);
        return $count->count ? $count->count : 0;
    }

    public function commissionAll()
    {
        $where['conditions'] = "order_status in (2,4,6)";
        $where['columns']    = "sum(money) as money";
        $money               = $this->findFirst($where);
        return $money->money ? $money->money : 0;
    }


}


